package com.lcm.learn.lcmcode.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @description:
 * @author: lcm
 * @create: 2020-01-19 09:16
 **/

public class SimpleJDKDynamicProxyDemo {

    public static void main(String[] args) {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        IService realService = new RealService();
        IService proxyService = (IService) Proxy.newProxyInstance(IService.class.getClassLoader(),
                new Class<?>[] { IService.class }, new SimpleInvocationHandler(realService));
        proxyService.sayHello();
        System.out.println(1);
    }

}

interface IService {
    void sayHello();
}

class RealService implements IService {

    @Override
    public void sayHello() {
        System.out.println("hello");
    }
}


class SimpleInvocationHandler implements InvocationHandler {
    private Object realObj;

    public SimpleInvocationHandler(Object realObj) {
        this.realObj = realObj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("entering " + method.getName());
        Object result = method.invoke(realObj, args);
        System.out.println("leaving " + method.getName());
        return result;
    }
}